import React, { useState, useRef, useEffect } from 'react';
import { FormattedMessage, useIntl } from 'umi';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import { Button, Modal, message, Upload, Alert } from 'antd';
import InvCheckModal from './InvCheckModal';
import request from '@/utils/request';
import UploadUtil from '@/components/UploadUtil';
import QuickMenu from '@/components/QuickMenu';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import OperpQuery from '@/components/OperpQuery';

const apiURL = '/api/services/app/PartBin/';
type PartBinItem = {
  id: string;
  onhandQty: number;
  avaQty: number;
  partNum: string;
  partDescription: string;
  ium: string;
  warehouseCode: string;
  binNum: string;
  lotNum: string;
};

const InvCheck: React.FC = () => {
  const [visible, setVisible] = useState(false);
  const [editStatus, setEditStatus] = useState(false);
  const [formVals, setFormVals] = useState({});
  const [params, setParams] = useState({});
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const [editSelectRow, setEditSelectRow] = useState<any>({});
  const [totOnhand, setTotOnhand] = useState(0);
  const [totAva, setTotAva] = useState(0);
  const [freshNum, setFreshNum] = useState(0);
  const [loading2, setLoading2] = useState(false);
  const [visible2, setVisible2] = useState(false);
  const [selectRows, setSelectRows] = useState<PartBinItem[]>([]);
  const proTbRef2 = useRef<ActionType>();
  const intl = useIntl();

  useEffect(() => {}, []);

  const switchVisible = (visible = false, formVals = {}, editStatus = false) => {
    setVisible(visible);
    setFormVals(formVals);
    setEditStatus(editStatus);
  };

  const handleSubmit = async (values: any) => {
    await request(apiURL + 'InvEdit', {
      method: 'POST',
      data: {
        partNum: values.partNum,
        whseCode: values.warehouseCode,
        binNum: values.binNum,
        qty: values.onhandQty,
        lotNum: values.lotNum,
      },
    }).then(() => {
      setFreshNum(freshNum + 1);
    });
    switchVisible();
  };

  const handlerImport = (info: any) => {
    setLoading2(true);
    if (info.file.status === 'done') {
      message.success(intl.formatMessage({ id: 'pages.import.success' }));
      setFreshNum(freshNum + 1);
      setLoading2(false);
    }
  };

  const doInvCheck = (_visible: boolean = false) => {
    if (selectRows.length <= 0 && _visible) {
      message.warning(intl.formatMessage({ id: 'pages.selectAtLeastOneRecord' }));
      return;
    }
    setVisible2(_visible);
  };

  const getNewSelectRows = async () => {
    return {
      data: selectRows,
      success: true,
    };
  };

  const checkQty = (rule: any, value: any, callback: any) => {
    if (value) {
      if (editSelectRow.avaQty < value || value <= 0) {
        callback(intl.formatMessage({ id: 'pages.onhandQuantityCheck' }));
      } else {
        callback();
      }
    } else {
      callback(intl.formatMessage({ id: 'pages.inspQty.required' }));
    }
  };

  const SpotCheck = (values: PartBinItem[]) => {
    request(apiURL + 'SpotCheck', {
      method: 'POST',
      data: values,
    }).then(() => {
      setFreshNum(freshNum + 1);
    });
    doInvCheck(false);
  };

  const rowSelection = {
    selectedRowKeys,
    onChange: (_selectedRowKeys: any, selectedRows: any) => {
      setSelectedRowKeys(_selectedRowKeys);
      setSelectRows(selectedRows);
    },
  };

  const columns2: ProColumns<PartBinItem>[] = [
    {
      title: <FormattedMessage id="pages.operation" />,
      valueType: 'option',
      key: 'option',
      render: (text, record, _, action) => [
        <a
          key="editable"
          onClick={() => {
            setEditSelectRow(record);
            action?.startEditable?.(record.id);
          }}
        >
          <FormattedMessage id="pages.edit" />
        </a>,
      ],
    },
    {
      title: <FormattedMessage id="pages.partNum" />,
      dataIndex: 'partNum',
      valueType: 'text',
      editable: false,
      ellipsis: true,
      width: 120,
    },
    {
      title: <FormattedMessage id="pages.partDescription" />,
      dataIndex: 'partDescription',
      valueType: 'text',
      editable: false,
      width: 200,
      ellipsis: true,
    },
    {
      title: <FormattedMessage id="pages.inspQty" />,
      dataIndex: 'onhandQty',
      valueType: 'digit',
      width: 120,
      formItemProps: {
        rules: [
          {
            required: true,
            validator: checkQty,
          },
        ],
      },
    },
    {
      title: <FormattedMessage id="pages.IUM" />,
      dataIndex: 'ium',
      valueType: 'text',
      width: 60,
      editable: false,
    },
    {
      title: <FormattedMessage id="pages.warehouseCode" />,
      dataIndex: 'warehouseCode',
      valueType: 'text',
      width: 100,
      editable: false,
    },
    {
      title: <FormattedMessage id="pages.binNum" />,
      dataIndex: 'binNum',
      valueType: 'text',
      width: 100,
      editable: false,
    },
    {
      title: <FormattedMessage id="pages.lotNum" />,
      dataIndex: 'lotNum',
      valueType: 'text',
      width: 100,
      ellipsis: true,
      editable: false,
    },
  ];

  return (
    <PageHeaderWrapper title={false} breadcrumbRender={false} ghost>
      <OperpQuery
        rowSelection={rowSelection}
        sysReportName="ReportInvCheck"
        scroll={{ x: 'max-content', y: '600px' }}
        freshNum={freshNum}
        callback={(record) => switchVisible(true, { ...record }, true)}
        onload={(data) => {
          let totOnhand = 0;
          let totAva = 0;
          data.forEach((element: any) => {
            totOnhand += element.onhandQty;
            totAva += element.avaQty;
          });
          setTotOnhand(totOnhand);
          setTotAva(totAva);
        }}
        toolBarRender={[
          <Alert message={intl.formatMessage({ id: 'pages.doubleClickEdit' })} type="warning" showIcon closable />,
          <a>
            {intl.formatMessage({ id: 'pages.totalInventory' })}：{totOnhand.toFixed(4)}，{intl.formatMessage({ id: 'pages.totalAvailable' })}：{totAva.toFixed(4)}
          </a>,
          <QuickMenu path="/part/InvCheck" icon="icon-todo_list" title="pages.InvCheck" />,
          <Button key="button" type="primary" onClick={() => switchVisible(true, {}, false)}>
            <FormattedMessage id="pages.create" />
          </Button>,
          <Upload
            accept=".xls,.xlsx,application/vnd.ms-excel"
            name="file"
            action="/api/Excel/ImportPartBin"
            headers={{
              Authorization: UploadUtil.accessToken,
            }}
            beforeUpload={UploadUtil.checkExcel}
            showUploadList={false}
            onChange={handlerImport}
          >
            <Button loading={loading2}>
              <span>
                <FormattedMessage id="pages.import" />
              </span>
            </Button>
          </Upload>,
          <Button key="button" type="primary" danger onClick={() => doInvCheck(true)}>
            <span>
              <FormattedMessage id="pages.spotCheck" />
            </span>
          </Button>,
        ]}
      />
      <Modal
        title={
          editStatus ? intl.formatMessage({ id: 'pages.stock.edit' }) : intl.formatMessage({ id: 'pages.stock.create' })
        }
        width="640px"
        bodyStyle={{ padding: 24 }}
        visible={visible}
        destroyOnClose
        footer={null}
        onCancel={() => setVisible(false)}
      >
        <InvCheckModal formVals={formVals} editStatus={editStatus} onSubmit={handleSubmit} />
      </Modal>
      <Modal
        title={intl.formatMessage({ id: 'pages.spotCheck' })}
        visible={visible2}
        destroyOnClose
        width="800px"
        footer={
          <Button key="button" type="primary" onClick={() => SpotCheck(selectRows)}>
            <FormattedMessage id="pages.submit" />
          </Button>
        }
        onCancel={() => doInvCheck(false)}
      >
        <ProTable<PartBinItem>
          actionRef={proTbRef2}
          columns={columns2}
          bordered
          request={async (params = {}) => {
            setParams(params);
            return getNewSelectRows();
          }}
          editable={{
            type: 'multiple',
            onSave: async (rowKey, data, row) => {
              const newArr: PartBinItem[] = [];
              selectRows.forEach((o: PartBinItem) => {
                if (o.id == row.id) {
                  newArr.push(data);
                } else {
                  newArr.push(o);
                }
              });
              setSelectRows(newArr);
              proTbRef2?.current?.reload();
            },
            onDelete: async (rowKey, row) => {
              const items = selectRows.filter((o: PartBinItem) => o.id != row.id);
              setSelectRows(items);
              proTbRef2?.current?.reload();
            },
          }}
          scroll={{ x: 'max-content', y: '300px' }}
          rowKey="id"
          search={false}
          pagination={false}
          headerTitle={false}
          toolBarRender={false}
        />
      </Modal>
    </PageHeaderWrapper>
  );
};

export default InvCheck;
